package cn.tedu.baking.controller;

import cn.tedu.baking.mapper.CommentMapper;
import cn.tedu.baking.mapper.ContentMapper;
import cn.tedu.baking.pojo.dto.CommentDTO;
import cn.tedu.baking.pojo.entity.Comment;
import cn.tedu.baking.pojo.ov.UserVO;
import cn.tedu.baking.response.JsonResult;
import cn.tedu.baking.response.StatusCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/comments")
public class CommentController {

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    ContentMapper contentMapper;


    @GetMapping("{id}")
    public JsonResult select(@PathVariable Long id) {
        return JsonResult.ok(commentMapper.selectByContentId(id));
    }

    @PostMapping("/add-new")
    public JsonResult addNew(@RequestBody CommentDTO commentDTO
            , HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDTO, comment);
        comment.setCreateTime(new Date());
        commentMapper.insert(comment);
        //让评论量+1
        contentMapper.updateCommentCountById(commentDTO.getContentId());
        return new JsonResult().ok();
    }
}
